<template>
  <BaseCharts
    ref="baseChartsRef"
    :options="options"
    autoRander
    :autoNumber="autoNumber"
  ></BaseCharts>
</template>

<script setup>
import BaseCharts from "@/components/echarts/vpt-base-chart/index.vue";
import { fontSize } from "@/utils/rem/rem.js";
import { watch, ref, onMounted, nextTick } from "vue";
import { getChartTootipFormatter } from "@/utils/formatter.js";
import { useEchart } from "@/hooks/useEchart.js";

const props = defineProps({
  chartType: { type: String, default: "init" },
  chartData: { type: Array, default: () => [] },
  // 横坐标数据
  xAxisData: { type: Array, default: () => [] },
  // y轴配置项
  yAxisProps: { type: Object, default: () => [] },
  // 内边距
  grid: { type: Object, default: () => ({}) },
  // 柱子颜色
  color: { type: Array, default: () => ["#1AC6FF"] },
  // 循环渲染
  autoRander: { type: Boolean, default: false },
  // 循环渲染间隔 单位S
  autoNumber: { type: Number, default: 60 },
  // 标题配置项
  titleProps: { type: Object, default: () => ({}) },
  // 滚动条配置
  dataZoom: { type: Object, default: () => ({}) },
  // 标题字号
  titleFontSize: { type: Number, default: 14 },
  // x轴标签字号
  xAxisLabelFontSize: { type: Number, default: 13 },
  // y轴标签字号
  yAxisLabelFontSize: { type: Number, default: 13 },
  // 柱子宽度
  barWidth: { type: Number, default: 20 },
  //是否显示legend
  showLegend: {
    type: Boolean,
    default: false,
  },
  //series name配置
  legendData: {
    type: Array,
    default: ["已完成", "未完成"],
  },
  rotate: {
    type: Number,
    default: 0,
  },
  // 横坐标间隔数据
  xAxisInterval: { type: [Number, String], default: () => 0 },
});

const fontColor = "rgba(29, 33, 41, 1)";
const options = ref({});
useEchart(getOptions);

const baseChartsRef = ref(null);

watch(
  () => ({ chartData: props.chartData, chartType: props.chartType }),
  () => {
    nextTick(async () => {
      if (props.chartType == "update") {
        updateSeries();
      } else {
        getOptions();
      }
    });
  },
  { deep: true }
);

function getOptions() {
  options.value = {
    // height: props.height,
    animation: false,
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
      textStyle: {
        fontFamily: "HarmonyOS_SansSC_Medium",
      },
      // borderColor: "transparent",
      // backgroundColor: "#0d1635cc",
      borderColor: "#fff",
      // extraCssText:
      //   "background: linear-gradient(180deg, #19406B, rgba(0, 134, 205, 0.91))", //渐变颜色
      formatter: (item) => {
        return getChartTootipFormatter(item);
      },
    },
    title: {
      text: "",
      textStyle: {
        color: "#fff",
        fontWeight: 400,
        fontFamily: "HarmonyOS_SansSC_Medium",
        fontSize: fontSize(props.titleFontSize),
      },
      ...props.titleProps,
    },
    grid: {
      left: 0,
      right: 0,
      bottom: 0,
      top: fontSize(140),
      containLabel: true,
      ...props.grid,
    },
    xAxis: [
      {
        data: props.xAxisData,
        // interval: 0,
        axisLabel: {
          show: true,
          color: fontColor,
          fontWeight: 400,
          fontSize: fontSize(props.xAxisLabelFontSize),
          fontFamily: "HarmonyOS_SansSC_Medium",
          rotate: props.rotate,
          interval: props.xAxisInterval,formatter: function (params) {
            var str = "";
            var paramsLen = params.length;
            var len = 6;
            var rowNumber = Math.ceil(paramsLen / len);
            if (paramsLen > len) {
              for (var i = 0; i < rowNumber; i++) {
                var temp = "";
                var start = i * len;
                var end = start + len;
                if (i == rowNumber - 1) {
                  temp = params.substring(start, paramsLen);
                } else {
                  temp = params.substring(start, end) + "\n";
                }
                str += temp;
              }
            } else {
              str = params;
            }
            return str;
          },
        },
        axisLine: {
          show: false,
        },
      },
    ],
    yAxis: [
      {
        type: "value",
        splitNumber: 4,
        axisLabel: {
          show: true,
          color: fontColor,
          fontWeight: 400,
          fontSize: fontSize(props.yAxisLabelFontSize),
          fontFamily: "HarmonyOS_SansSC_Medium",
        },
        splitLine: {
          show: true, // 是否显示网格线
          lineStyle: {
            // 网格线的样式
            color: "#f3f4f5", // 颜色
            type: "dashed", // 类型
          },
        },
        nameTextStyle: {
          fontSize: fontSize(props.yAxisLabelFontSize),
          color: fontColor,
          fontFamily: "HarmonyOS_SansSC_Medium",
          fontWeight: 400,
        },
        ...props.yAxisProps,
      },
    ],
    series: props.chartData.map((item, index) => {
      return {
        name: props.legendData[index],
        type: "bar",
        stack: "workOrder",
        barWidth: fontSize(props.barWidth),
        data: item,
        color: props.color[index],
      };
    }),
    dataZoom: {
      show: false,
      height: 6,
      bottom: fontSize(12),
      showDetail: false,
      startValue: 0,
      endValue: 7, // 可视窗口下显示的数量, 设置endValue值被当作数据的index取值
      borderWidth: 0,
      handleSize: 0,
      showDataShadow: false,
      brushSelect: false,
      rangeMode: "value",
      fillerColor: "#0000001a",
      backgroundColor: "#fff", //两边未选中的滑动条区域的颜色
      borderColor: "transparent",
      moveHandleSize: 0,
      zoomLock: true,
      handleStyle: {
        color: "#00000029",
        borderWidth: 0,
      },
      ...props.dataZoom,
    },
    legend: {
      selectedMode: false,
      show: props.showLegend,
      top: 0,
      left: "left",
      itemWidth: fontSize(12),
      itemHeight: fontSize(12),
      textStyle: {
        color: "#4E5969",
        fontSize: fontSize(12),
        fontFamily: "HarmonyOS_SansSC_Medium",
      },
      data: props.legendData,
    },
  };
}

function getEchartsInstance() {
  return new Promise((resolve) => {
    baseChartsRef.value.commonFunc((instance) => resolve(instance));
  });
}

// 更新图表
async function updateSeries() {
  try {
    const chartInstance = await getEchartsInstance();
    if (chartInstance) {
      const newChartOption = chartInstance.getOption();
      // 遍历 series 更新 data
      newChartOption.series[0].data = props.chartData[0];
      newChartOption.series[1].data = props.chartData[1];
      newChartOption.xAxis[0].data = props.xAxisData;
      if (!props.xAxisData.length) {
        newChartOption.legend[0].data = [];
      } else {
        newChartOption.legend[0].data = props.legendData;
      }

      newChartOption.dataZoom[0] = props.dataZoom;
      // 更新 series 部分
      chartInstance.setOption(newChartOption, false);
      // 更新 series 部分
      chartInstance.setOption(newChartOption, false);
    }
  } catch (error) {
    // console.error("Failed to update chart:", error);
  }
}

defineExpose({
  reloadEchart: () => {
    baseChartsRef.value.reloadEchart();
  },
});
</script>
